package clock.socoolby.com.clock;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.PermissionUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.fadai.particlesmasher.ParticleSmasher;
import com.fadai.particlesmasher.SmashAnimator;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import clock.socoolby.com.clock.pop.CalendarPopup;
import clock.socoolby.com.clock.pop.ColorPickerPop;
import clock.socoolby.com.clock.pop.WeatherPopup;
import clock.socoolby.com.clock.protocol.WeatherResponse;
import clock.socoolby.com.clock.model.DateModel;
import clock.socoolby.com.clock.service.ProximityService;
import clock.socoolby.com.clock.utils.FontUtils;
import clock.socoolby.com.clock.utils.Player;
import clock.socoolby.com.clock.utils.ScreenManager;
import clock.socoolby.com.clock.model.SharePerferenceModel;
import clock.socoolby.com.clock.pop.TimeSetupPopup;
import clock.socoolby.com.clock.widget.animatorview.AnimatorView;
import clock.socoolby.com.clock.widget.animatorview.I_Animator;
import clock.socoolby.com.clock.widget.animatorview.animator.BubbleAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.BubbleCollisionAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.BubbleWhirlPoolAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.CarrouselAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.ClockAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.DotsLineAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.PhaserBallAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.Wave3DAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.clockanimator.AbstractClock;
import clock.socoolby.com.clock.widget.animatorview.animator.clockanimator.CircleClock;
import clock.socoolby.com.clock.widget.animatorview.animator.clockanimator.HelixClock;
import clock.socoolby.com.clock.widget.animatorview.animator.clockanimator.HexagonalClock;
import clock.socoolby.com.clock.widget.animatorview.animator.clockanimator.OctagonalClock;
import clock.socoolby.com.clock.widget.animatorview.animator.clockanimator.OvalClock;
import clock.socoolby.com.clock.widget.animatorview.animator.clockanimator.SquareClock;
import clock.socoolby.com.clock.widget.animatorview.animator.textanimator.EZLedAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.FireAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.FireworkAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.FluorescenceAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.RainAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.RippleAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.SkyAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.SnowAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.StarFallAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.VorolayAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.WaterAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.WindmillAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.textanimator.EvaporateTextAnimator;
import clock.socoolby.com.clock.widget.animatorview.animator.textanimator.PathEffectTextAnimator;
import clock.socoolby.com.clock.widget.textview.AutoScrollTextView;
import clock.socoolby.com.clock.widget.textview.DigitTextView;


public class MainActivity extends Activity implements Handler.Callback, View.OnClickListener, android.view.GestureDetector.OnGestureListener, ScaleGestureDetector.OnScaleGestureListener, GestureDetector.OnDoubleTapListener {
    private final static String TAG = MainActivity.class.getSimpleName();
    private final static int SETTING_REQUEST_CODE = 100;

    public final static int MODE_NORMAL = 200;
    public final static int MODE_SETTING_OTHER = 202;
    public final static int MODE_HANDUP=203;
    public final static int MODE_FULLSCREEN=204;


    public class TimeFontStyle{
       String name;
       int displaySecond;
       int noDisplaySecond;
       int displaySecondOnFull;
       int noDisplaySecondOnFull;
       float secondScale;

       public TimeFontStyle(String name, int displaySecond, int noDisplaySecond) {
           this(name,displaySecond,noDisplaySecond,displaySecond,noDisplaySecond);
       }

       public TimeFontStyle(String name, int displaySecond, int noDisplaySecond, int displaySecondOnFull, int noDisplaySecondOnFull) {
           this(name,displaySecond,noDisplaySecond,displaySecondOnFull,noDisplaySecondOnFull,1/2);
       }

       public TimeFontStyle(String name, int displaySecond, int noDisplaySecond, int displaySecondOnFull, int noDisplaySecondOnFull, float second) {
           this.name = name;
           this.displaySecond = displaySecond;
           this.noDisplaySecond = noDisplaySecond;
           this.displaySecondOnFull = displaySecondOnFull;
           this.noDisplaySecondOnFull = noDisplaySecondOnFull;
           this.secondScale = second;
       }
   }

   private List<TimeFontStyle> fontStyleList;

   private void initTimeFontStyle(){
       fontStyleList=new ArrayList<>();
       fontStyleList.add(new TimeFontStyle("affair",110,120,130,150));
       fontStyleList.add(new TimeFontStyle("agenda",140,150,160,180));

       fontStyleList.add(new TimeFontStyle("cheapfire",140,150,160,180));
       fontStyleList.add(new TimeFontStyle("cherif",80,100,110,140));
       fontStyleList.add(new TimeFontStyle("Cigar Box Guitar",120,130,140,150));
       fontStyleList.add(new TimeFontStyle("Ciung Wanara Sejati",110,120,130,150));


       fontStyleList.add(new TimeFontStyle("DK Bergelmir",120,130,140,180));
       fontStyleList.add(new TimeFontStyle("ds_digi",140,150,160,200));


       fontStyleList.add(new TimeFontStyle("Funk",110,120,130,150));

       fontStyleList.add(new TimeFontStyle("GLADYS Regular",110,120,130,150));
       fontStyleList.add(new TimeFontStyle("Granite Rock St",110,120,130,170));
       fontStyleList.add(new TimeFontStyle("GROOT",120,130,140,170));


       fontStyleList.add(new TimeFontStyle("juleslove",110,120,130,150));

       fontStyleList.add(new TimeFontStyle("Kingthings Annexx",110,120,150,180));
       fontStyleList.add(new TimeFontStyle("Kingthings Willow",110,120,130,150));
       fontStyleList.add(new TimeFontStyle("KYLE Regular",110,120,130,150));

       fontStyleList.add(new TimeFontStyle("LCD-U",130,140,150,180));
       fontStyleList.add(new TimeFontStyle("loong07龙书势如破竹简",110,120,150,170));

       fontStyleList.add(new TimeFontStyle("MILKDROP",110,120,130,160));
       fontStyleList.add(new TimeFontStyle("Mosaicleaf086",110,120,130,150));


       fontStyleList.add(new TimeFontStyle("Pro Display tfb",130,140,150,170));

       fontStyleList.add(new TimeFontStyle("SailingJunco",130,140,150,200));
       fontStyleList.add(new TimeFontStyle("scoreboard",120,130,140,190));
       fontStyleList.add(new TimeFontStyle("SFWasabi-Bold",110,120,130,140));
       fontStyleList.add(new TimeFontStyle("Spaghettica",110,120,130,150));

       fontStyleList.add(new TimeFontStyle("the_vandor_spot",140,150,160,210));

       fontStyleList.add(new TimeFontStyle("Woodplank",120,130,140,180));
       fontStyleList.add(new TimeFontStyle("Xtra Power",100,110,120,160));

       fontStyleList.add(new TimeFontStyle("海报圆圆",110,120,130,150));
       fontStyleList.add(new TimeFontStyle("爱心小兔",110,115,130,140));
       fontStyleList.add(new TimeFontStyle("王漢宗海報體一半天水",110,120,130,150));
       fontStyleList.add(new TimeFontStyle("立体铁山硬笔行楷简",120,130,140,180));
       fontStyleList.add(new TimeFontStyle("腾祥倩心简",110,120,130,150));
       fontStyleList.add(new TimeFontStyle("苏新诗毛糙体简",110,120,130,150));
       fontStyleList.add(new TimeFontStyle("谁能许我扶桑花期",110,120,130,150));
       fontStyleList.add(new TimeFontStyle("造字工房凌黑",110,120,130,150));
       fontStyleList.add(new TimeFontStyle("中国龙新草体",110,120,130,150));
       fontStyleList.add(new TimeFontStyle("迷你简剪纸_0",110,120,130,150));
   }

    private void updateTimeFontSize(){
       setFontSize(getCurrentFontSize());
    }

    private int getCurrentFontSize(){
        TimeFontStyle fontStyle=fontStyleList.get(currentFontIndex);
        int fontSize=fontStyle.displaySecond;
        if(isFullScreen){
            if(model.isDisplaySecond()) {
                fontSize=fontStyle.displaySecondOnFull;
            }else{
                fontSize=fontStyle.noDisplaySecondOnFull;
            }
        }else{
            if(model.isDisplaySecond()) {
                fontSize=fontStyle.displaySecond;
            }else{
                fontSize=fontStyle.noDisplaySecond;
            }
        }
        return fontSize;
    }

    private int getMaxFontSize(){
        TimeFontStyle fontStyle=fontStyleList.get(currentFontIndex);
        int fontSize=fontStyle.displaySecond;
        if(model.isDisplaySecond()) {
             fontSize=fontStyle.displaySecondOnFull;
        }else{
             fontSize=fontStyle.noDisplaySecondOnFull;
        }
        return fontSize;
    }

    private int currentFontIndex =4;

    protected void setFont(int index){
        currentFontIndex =index;
        if(currentFontIndex >fontStyleList.size())
            currentFontIndex =4;
        TimeFontStyle fontStyle=fontStyleList.get(index);
        String timeString=tv_time.getText().toString();
        Log.d(TAG,"befor setFont text:"+timeString+"\t witch:"+tv_time.getWidth()+"\t height:"+tv_time.getHeight());
        Log.d(TAG,"setFont  index:"+index+"/t name:"+fontStyle.name+".ttf/t ");
        FontUtils.getInstance().replaceFontFromAsset(tv_time,"fonts/"+fontStyle.name+".ttf");
        FontUtils.getInstance().replaceFontFromAsset(tv_date,"fonts/"+fontStyle.name+".ttf");
        updateTimeFontSize();
        Log.d(TAG,"after setFont text:"+tv_time.getText()+"\t witch:"+tv_time.getWidth()+"\t height:"+tv_time.getHeight());
    }

    private void setFontSize(int fontSize){
        tv_time.setTextSize(fontSize);
    }


    private DigitTextView tv_time;
    private TextView tv_date;
    private TextView tv_day;
    private TextView tv_weather;
    private AutoScrollTextView tv_descript;
    private ImageButton tv_setting;
    private ImageButton tv_handup;
    private TextView tv_handup_image;

    private TextView tv_hand_time;
    private boolean hand_time_visable=true;

    private  Timer timer;
    private Handler handler;
    private final static int UPDATE_TIME = 100;

    //背景动画
    private AnimatorView animatorView;

    private I_Animator backGroundAnimator;

    private int currectAnimatorIndex=0;

    private final static int ANIMATOR_TEXTLED=80;

    //前景动画
    private AnimatorView clockView;

    private int currentClockAnimatorIndex=0;

    private ImageButton tv_hours_system;
    //颜色相关
    private ImageButton tv_background_color;
    private ImageButton tv_foreground_color;
    private ImageButton tv_foreground_color1;

    //背景图相关
    private ImageButton tv_background_image_hand;
    private ImageView tv_background_image;
    private String imagePath=null;

    ColorPickerPop colorPickerDialog;

    // 定义手势检测器实例
    GestureDetector detector;
    ScaleGestureDetector scaleGestureDetector;

    private PowerManager.WakeLock wakeLock = null;


    private SharePerferenceModel model;

    private PowerManager.WakeLock localWakeLock = null;

    public int mMode = MODE_NORMAL;

    private int brightness = 0;

    private boolean handUpAbla=false;
    private int handUpTime=-1;
    WeatherResponse weatherAdape;

    private boolean screenLock=false;
    private ImageButton tv_screen_lock;

    private Integer backgroundColor;
    private Integer foregroundColor;
    private FrameLayout mainBackground;



    public void setWeather(WeatherResponse weather) {
        if (weather == null)
            return;
        Log.d(TAG,"setWeather...");
        this.weatherAdape= weather;
        if (weather.getTodayWeather() != null)
            tv_weather.setText(weather.getTodayWeather().weather+"/"+weather.getTodayWeather().temperature);
    }
    TimerTask timerTask;

    @SuppressLint("InvalidWakeLockTag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Log.d(TAG,"onCreate...");
        setContentView(R.layout.activity_main);
        mainBackground=findViewById(R.id.main_background);
        tv_background_image=findViewById(R.id.tv_background_image);
        tv_background_image_hand=findViewById(R.id.tv_background_image_hand);
        tv_background_image_hand.setOnClickListener(this);
        tv_background_image_hand.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                configBackGroundImage();
                return true;
            }
        });

        animatorView=findViewById(R.id.tv_background_animatorview);

        clockView=findViewById(R.id.tv_foreground_animatorview);

        tv_time = findViewById(R.id.tv_time);
        //tv_time.setOnClickListener(this);

        tv_date = findViewById(R.id.tv_date);
        tv_date.setOnClickListener(this);


        tv_day =  findViewById(R.id.tv_day);
        tv_day.setOnClickListener(this);
        tv_day.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if(screenLock)
                    return true;
                model.setHourSystem12(!model.isHourSystem12());
                model.save();
                updateHourSystem();
                return true;
            }
        });

        tv_weather = findViewById(R.id.tv_weather);
        tv_weather.setOnClickListener(this);
        tv_descript =  findViewById(R.id.tv_descript);
        tv_descript.setOnClickListener(this);
        tv_descript.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                changeBackGroundAnimator(ANIMATOR_TEXTLED);
                return true;
            }
        });

        tv_handup=findViewById(R.id.tv_hand);
        tv_handup.setOnClickListener(this);
        tv_handup.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                if(screenLock)
                    return true;
                setupHandUpTime();
                return true;
            }
        });
        tv_hand_time=findViewById(R.id.tv_hand_time);
        tv_hand_time.setOnClickListener(this);
        tv_hand_time.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                hand_time_visable=false;
                tv_hand_time.setVisibility(View.GONE);
                return true;
            }
        });

        tv_hours_system=findViewById(R.id.tv_hours_system);

        tv_background_color=findViewById(R.id.tv_background_color);
        tv_background_color.setOnClickListener(this);

        tv_foreground_color=findViewById(R.id.tv_foreground_color);
        tv_foreground_color.setOnClickListener(this);
        tv_foreground_color.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if(screenLock)
                    return true;
                if (colorPickerDialog == null)
                    colorPickerDialog = new ColorPickerPop(MainActivity.this);

                colorPickerDialog.setOnColorChangeListenter(new ColorPickerPop.OnColorListener() {
                    @Override
                    public void onEnsure(int color) {

                        model.setForegroundColor(color);
                        model.save();
                        setForegroundColor(color);
                        tv_foreground_color.setColorFilter(color);
                    }

                    @Override
                    public void onBack() {
                    }
                });
                colorPickerDialog.show(model.getForegroundColor());
                return true;
            }
        });

        tv_foreground_color1=findViewById(R.id.tv_foreground_color1);
        tv_foreground_color1.setOnClickListener(this);
        tv_foreground_color1.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if(screenLock)
                    return true;
                if (colorPickerDialog == null)
                    colorPickerDialog = new ColorPickerPop(MainActivity.this);

                colorPickerDialog.setOnColorChangeListenter(new ColorPickerPop.OnColorListener() {
                    @Override
                    public void onEnsure(int color) {
                        model.setForegroundColor1(color);
                        model.save();
                        setForegroundColor(color);
                        tv_foreground_color1.setColorFilter(color);
                        animatorView.setColor(color);
                    }

                    @Override
                    public void onBack() {
                    }
                });
                colorPickerDialog.show(model.getForegroundColor1());
                return true;
            }
        });

        tv_handup_image=findViewById(R.id.tv_handup_image);
        tv_handup_image.setOnClickListener(this);


        handler = new Handler(this);
        tv_setting = findViewById(R.id.tv_setting);
        tv_setting.setOnClickListener(this);

        //RelativeLayout rel_main = (RelativeLayout) findViewById(R.id.rel_main);
        //rel_main.setOnClickListener(this);

        tv_screen_lock =findViewById(R.id.tv_screen_lock);
        tv_screen_lock.setOnClickListener(this);
        tv_screen_lock.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                screenLock(true);
                switchMode(MODE_FULLSCREEN);
                return true;
            }
        });


            if(PermissionUtils.isGranted("android.permission.WAKE_LOCK","android.permission.DEVICE_POWER")) {
                PowerManager powerManager = (PowerManager) this.getSystemService(POWER_SERVICE);
                wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK |powerManager.ON_AFTER_RELEASE, "Clock");
                localWakeLock = powerManager.newWakeLock(32, "MyPower");
            }else
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);


        //创建手势检测器
        detector = new GestureDetector(this, this);
        detector.setOnDoubleTapListener(this);

        scaleGestureDetector=new ScaleGestureDetector(this,this);

        init();
        ClockApplication.getInstance().setMainActivity(this);

         //Log.d(TAG,"create timer and timerTask.................................");
         timer = new Timer();
         timerTask = new TimerTask() {
             @Override
             public void run() {
                  //Log.d(TAG, "timerTask move...");
                 if (!ScreenManager.isScreenOn())
                     return;
                  handler.sendEmptyMessage(UPDATE_TIME);
          }
          };
         timer.schedule(timerTask, 1000, 1000);
        //ClockApplication.getInstance().getBusinessService().checkUpdate();
    }


    private boolean isPowerManagerDisable(){
        return wakeLock==null;
    }

    private void setUpProximityService(){
        if(isPowerManagerDisable())
            return;
        try{
            if(screenLock){
               stopService(proximityServiceIntent);
            }else {
                if (model.isTriggerScreen()) {
                    startService(proximityServiceIntent);
                } else {
                    stopService(proximityServiceIntent);
                }
             }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    private void onRequestPermissions(int reqCode,String  ...permissions){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!PermissionUtils.isGranted(permissions)) {
                ActivityCompat.requestPermissions(this,
                        permissions,
                        reqCode);
            }else {
                //Toast.makeText(this,"权限已申请",Toast.LENGTH_LONG).show();
            }
        }
    }

    Intent proximityServiceIntent=null;

    private void init() {
        model = new SharePerferenceModel();
        model.read();
        initTimeFontStyle();
        Log.d(TAG, "init model:" + model.toString());
        setDiscriptForModel();
        proximityServiceIntent = new Intent(this, ProximityService.class);
        setUpProximityService();

        brightness=getSystemBrightness();
        handUpAbla=model.isHandUpAble();
        resetColorFromModel();
        setFont(model.getFontIndex()==null?0:model.getFontIndex());
        upHandStatic();
        resetHandUpTime();
        updateHourSystem();
    }

    private void resetColorFromModel(){
        setBackGroundColor(model.getBackgroundColor());
        setForegroundColor(model.getForegroundColor());
        tv_foreground_color.setColorFilter(model.getForegroundColor());
        tv_foreground_color1.setColorFilter(model.getForegroundColor1());
        animatorView.setColor(model.getForegroundColor1());
    }


    private void updateHourSystem(){
        if(model.isHourSystem12())
            tv_hours_system.setVisibility(View.VISIBLE);
        else
            tv_hours_system.setVisibility(View.GONE);
    }

    //将该Activity上的触碰事件交给GestureDetector处理
    @Override
    public boolean onTouchEvent(MotionEvent me)
    {
        if(me.getPointerCount()>1)
            return scaleGestureDetector.onTouchEvent(me);
        return detector.onTouchEvent(me);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //Log.d(TAG,"onRestart...");
    }

    @Override
    public void onDestroy() {
        //Log.i(TAG, "onDestroy....");
        super.onDestroy();
        timer.cancel();
        try {
            if (model.isTriggerScreen())
                stopService(proximityServiceIntent);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(backGroundAnimator!=null)
            backGroundAnimator.stop();

    }


    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected void onResume() {
        //Log.i(TAG, "onDestroy....");
        super.onResume();
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        if(!isPowerManagerDisable())
            wakeLock.acquire();
        if(backGroundAnimator!=null)
            backGroundAnimator.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //Log.d(TAG,"onPause..");
        if(!isPowerManagerDisable())
            wakeLock.release();
        if(backGroundAnimator!=null)
            backGroundAnimator.stop();
    }

    private String backGroundImagePath=null;
    private void configBackGroundImage(){
        PictureSelector.create(MainActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .imageSpanCount(4)
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的

                    backGroundImagePath=selectList.get(0).getPath();

                    RequestOptions options = new RequestOptions();
                    options.centerCrop();
                    tv_background_image.setVisibility(View.VISIBLE);
                    Glide.with(MainActivity.this)
                            .load(selectList.get(0).getPath())
                            .apply(options)
                            .into(tv_background_image);
                    break;
                case SETTING_REQUEST_CODE:
                    init();
                    break;
            }
        }
    }

    protected void setForegroundColor(Integer color){
        if(foregroundColor!=null&&foregroundColor==color)
            return;
        foregroundColor=color;
        tv_time.setTextColor(color);
        tv_date.setTextColor(color);
        tv_day.setTextColor(color);
        tv_weather .setTextColor(color);
        tv_descript.setTextColor(color);
        tv_handup_image.setTextColor(color);

        tv_handup.setColorFilter(color);
        tv_screen_lock.setColorFilter(color);
        tv_setting.setColorFilter(color);
        tv_background_color.setColorFilter(color);
        tv_hand_time.setTextColor(color);
        tv_hours_system.setColorFilter(color);
        tv_background_image_hand.setColorFilter(color);
    }

    protected void setBackGroundColor(Integer color){
        if(backgroundColor!=null&&backgroundColor==color)
            return;
        backgroundColor=color;
        mainBackground.setBackgroundColor(color);
    }

    CalendarPopup calendarPopup;
    WeatherPopup weatherPopup;
    ParticleSmasher particleSmasher;
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onClick(View view) {
        if(screenLock&&view.getId()!=R.id.tv_screen_lock&&view.getId()!=R.id.tv_handup_image) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_setting:
               setup();
               break;
            case R.id.tv_hand:
                if(!handUpAbla&&handUpTime<0) {
                    setupHandUpTime();
                }else{
                    handUpAbla=!handUpAbla;
                    saveData();
                    upHandStatic();
                    resetHandUpTime();
                    switchMode(MODE_NORMAL);
                }
                break;
            case R.id.tv_hand_time:
                setupTempHandUpTime();
                break;
            case R.id.tv_handup_image:
                switchMode(MODE_NORMAL);
                break;
            case R.id.tv_day:
                model.setDisplaySecond(!model.isDisplaySecond());
                model.save();
                updateTimeFontSize();
                break;
            case R.id.tv_date:
                if( calendarPopup ==null)
                    calendarPopup =new CalendarPopup(this);
                calendarPopup.showPopupWindow();
                calendarPopup.setCurrentDay();
                break;
            case R.id.tv_weather:
                if( weatherPopup ==null)
                    weatherPopup =new WeatherPopup(this);
                weatherPopup.init(weatherAdape.getWeatherList(),model.getCity()+"    PM2.5 : "+weatherAdape.getmPM25());
                weatherPopup.showPopupWindow();
                break;
            case R.id.tv_screen_lock:
                if(isFullScreen) {
                    isArtificialHiddle=false;
                    fullScreen(false);
                }
                screenLock(!screenLock);
                break;
            case R.id.tv_descript:
                setDiscript(SettingActivity.roundAutoQuotes());
                break;
            case R.id.tv_background_color:
                if (colorPickerDialog == null)
                    colorPickerDialog = new ColorPickerPop(MainActivity.this);

                colorPickerDialog.setOnColorChangeListenter(new ColorPickerPop.OnColorListener() {
                    @Override
                    public void onEnsure(int color) {
                        model.setBackgroundColor(color);
                        model.save();
                        setBackGroundColor(color);
                    }
                    @Override
                    public void onBack() {
                    }
                });
                colorPickerDialog.show(model.getBackgroundColor());
                break;
            case R.id.tv_background_image_hand:
                 if(backGroundImagePath==null)
                     configBackGroundImage();
                 else
                     tv_background_image.setVisibility(tv_background_image.getVisibility()==View.VISIBLE?View.GONE:View.VISIBLE);
            case R.id.tv_foreground_color:
                setForegroundColor(model.getForegroundColor());
                break;
            case R.id.tv_foreground_color1:
                setForegroundColor(model.getForegroundColor1());
                break;
        }
    }


    public void screenLock(boolean locked){
        screenLock=locked;
        tv_screen_lock.setImageResource(screenLock?R.drawable.ic_screen_lock:R.drawable.ic_screen_unlock);
        setUpProximityService();
    }

    private int prevMode=MODE_NORMAL;
    private boolean isArtificialHiddle=false;
    private boolean isFullScreen=false;
    private void switchMode(int mode) {
        Log.d(TAG,"switch mode to:"+mode);
        switch (mode) {
            case MODE_FULLSCREEN:
                 fullScreen(true);
                 break;
            case MODE_NORMAL:
                if(isFullScreen){
                    if(!isArtificialHiddle)
                       tv_time.setVisibility(View.VISIBLE);
                    tv_handup_image.setVisibility(View.GONE);
                }else {
                    tv_time.setVisibility(View.VISIBLE);
                    tv_handup_image.setVisibility(View.GONE);
                    tv_setting.setVisibility(View.GONE);
                    tv_background_color.setVisibility(View.GONE);
                    tv_foreground_color.setVisibility(View.GONE);
                    tv_foreground_color1.setVisibility(View.GONE);
                    tv_background_image_hand.setVisibility(View.GONE);
                }
                break;
            case MODE_SETTING_OTHER:
                tv_time.setVisibility(View.VISIBLE);
                tv_handup_image.setVisibility(View.GONE);
                tv_setting.setVisibility(View.VISIBLE);
                tv_background_color.setVisibility(View.VISIBLE);
                tv_foreground_color.setVisibility(View.VISIBLE);
                tv_foreground_color1.setVisibility(View.VISIBLE);
                tv_background_image_hand.setVisibility(View.VISIBLE);
                break;
            case MODE_HANDUP:
                if(isFullScreen){
                    tv_time.setVisibility(View.GONE);
                    tv_handup_image.setVisibility(View.VISIBLE);
                }else {
                    tv_time.setVisibility(View.GONE);
                    tv_handup_image.setVisibility(View.VISIBLE);
                    tv_setting.setVisibility(View.GONE);
                    tv_background_color.setVisibility(View.GONE);
                    tv_foreground_color.setVisibility(View.GONE);
                    tv_foreground_color1.setVisibility(View.GONE);
                    tv_background_image_hand.setVisibility(View.GONE);
                    setDiscriptForModel();
                }
        }
        prevMode=mMode;
        mMode = mode;
    }

    private void fullScreen(boolean fullable){
        isFullScreen=fullable;
        if(fullable) {
            // @tudo 可对其时行位置移动
            //tv_time.setVisibility(View.GONE);
            tv_date.setVisibility(View.GONE);
            tv_day.setVisibility(View.GONE);
            tv_weather.setVisibility(View.GONE);
            tv_descript.setVisibility(View.GONE);
            tv_handup_image.setVisibility(View.GONE);

            tv_handup.setVisibility(View.GONE);

            tv_setting.setVisibility(View.GONE);
            tv_background_color.setVisibility(View.GONE);
            //tv_hand_time.setTextColor(color);

            tv_background_color.setVisibility(View.GONE);
            tv_foreground_color.setVisibility(View.GONE);
            tv_foreground_color1.setVisibility(View.GONE);
            tv_background_image_hand.setVisibility(View.GONE);
        }else{
            if(clockView.isRunning()) {
                //clockView.setAnimator(null);
                clockView.stop();
            }
            clockView.setVisibility(View.GONE);
            tv_time.setVisibility(View.VISIBLE);
            tv_date.setVisibility(View.VISIBLE);
            tv_day.setVisibility(View.VISIBLE);
            tv_weather.setVisibility(View.VISIBLE);
            tv_descript.setVisibility(View.VISIBLE);
            tv_handup_image.setVisibility(View.VISIBLE);

            tv_handup.setVisibility(View.VISIBLE);

            if(prevMode==MODE_HANDUP)
                switchMode(MODE_NORMAL);
            else
                switchMode(prevMode);
        }
        updateTimeFontSize();
    }

    StarFallAnimator starAnimator;
    SkyAnimator skyAnimator;
    RainAnimator rainAnimator;
    SnowAnimator snowAnimator;
    BubbleWhirlPoolAnimator bubbleWhirlPoolAnimator;
    BubbleAnimator bubbleAnimator;
    FluorescenceAnimator fluorescenceAnimator;
    BubbleCollisionAnimator bubbleCollisionAnimator;
    FireworkAnimator fireworkAnimator;
    DotsLineAnimator dotsLineAnimator;
    WaterAnimator waterAnimator;
    FireAnimator fireAnimator;
    RippleAnimator rippleAnimator;
    WindmillAnimator windmillAnimator;
    VorolayAnimator vorolayAnimator;
    EZLedAnimator eZLedAnimator;
    EvaporateTextAnimator evaporateTextAnimator;
    PhaserBallAnimator phaserBallAnimator;
    CarrouselAnimator carrouselAnimator;
    Wave3DAnimator wave3DAnimator;
    public void changeBackGroundAnimator(int index){
        switch(index){
            case 0:
                if(starAnimator==null) {
                    starAnimator = new StarFallAnimator();
                    starAnimator.init(animatorView.getContext(),animatorView);
                    starAnimator.setColor(foregroundColor);
                }
                backGroundAnimator=starAnimator;
                backGroundAnimator.setRandColor(false);
                break;
            case 2:
                if(phaserBallAnimator ==null) {
                    phaserBallAnimator = new PhaserBallAnimator();
                    phaserBallAnimator.init(animatorView.getContext(),animatorView);
                    phaserBallAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= phaserBallAnimator;
                backGroundAnimator.setRandColor(true);
                break;
            case 3:
                if(rainAnimator==null) {
                    rainAnimator = new RainAnimator();
                    rainAnimator.init(animatorView.getContext(),animatorView);
                    rainAnimator.setColor(foregroundColor);
                }
                backGroundAnimator=rainAnimator;
                backGroundAnimator.setRandColor(false);
                break;
            case 4:
                if(snowAnimator==null) {
                    snowAnimator = new SnowAnimator();
                    snowAnimator.init(animatorView.getContext(),animatorView);
                    snowAnimator.setColor(foregroundColor);
                }
                backGroundAnimator=snowAnimator;
                backGroundAnimator.setRandColor(false);
                break;
            case 5:
                if(starAnimator==null) {
                    starAnimator = new StarFallAnimator();
                    starAnimator.init(animatorView.getContext(),animatorView);
                    starAnimator.setColor(foregroundColor);
                }
                backGroundAnimator=starAnimator;
                backGroundAnimator.setRandColor(true);
                break;
            case 6:
                if(skyAnimator==null) {
                    skyAnimator = new SkyAnimator();
                    skyAnimator.init(animatorView.getContext(),animatorView);
                    skyAnimator.setColor(foregroundColor);
                }
                backGroundAnimator=skyAnimator;
                backGroundAnimator.setRandColor(true);
                break;
            case 7:
                if(rainAnimator==null) {
                    rainAnimator = new RainAnimator();
                    rainAnimator.init(animatorView.getContext(),animatorView);
                    rainAnimator.setColor(foregroundColor);
                }
                backGroundAnimator=rainAnimator;
                backGroundAnimator.setRandColor(true);
                break;
            case 8:
                if(snowAnimator==null) {
                    snowAnimator = new SnowAnimator();
                    snowAnimator.init(animatorView.getContext(),animatorView);
                    snowAnimator.setColor(foregroundColor);
                }
                backGroundAnimator=snowAnimator;
                backGroundAnimator.setRandColor(true);
                break;
            case 9:
                if(bubbleWhirlPoolAnimator ==null) {
                    bubbleWhirlPoolAnimator = new BubbleWhirlPoolAnimator();
                    bubbleWhirlPoolAnimator.init(animatorView.getContext(),animatorView);
                    bubbleWhirlPoolAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= bubbleWhirlPoolAnimator;
                backGroundAnimator.setRandColor(false);
                break;
            case 10:
                if(bubbleAnimator ==null) {
                    bubbleAnimator = new BubbleAnimator();
                    bubbleAnimator.init(animatorView.getContext(),animatorView);
                    bubbleAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= bubbleAnimator;
                backGroundAnimator.setRandColor(false);
                break;
            case 11:
                if(bubbleAnimator ==null) {
                    bubbleAnimator = new BubbleAnimator();
                    bubbleAnimator.init(animatorView.getContext(),animatorView);
                    bubbleAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= bubbleAnimator;
                backGroundAnimator.setRandColor(true);
                break;
            case 12:
                if(bubbleWhirlPoolAnimator ==null) {
                    bubbleWhirlPoolAnimator = new BubbleWhirlPoolAnimator();
                    bubbleWhirlPoolAnimator.init(animatorView.getContext(),animatorView);
                    bubbleWhirlPoolAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= bubbleWhirlPoolAnimator;
                backGroundAnimator.setRandColor(true);
                break;
            case 13:
                if(fluorescenceAnimator ==null) {
                    fluorescenceAnimator = new FluorescenceAnimator();
                    fluorescenceAnimator.init(animatorView.getContext(),animatorView);
                    fluorescenceAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= fluorescenceAnimator;
                //backGroundAnimator.setRandColor(true);
                break;
            case 14:
                if(bubbleCollisionAnimator ==null) {
                    bubbleCollisionAnimator = new BubbleCollisionAnimator();
                    bubbleCollisionAnimator.init(animatorView.getContext(),animatorView);
                    bubbleCollisionAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= bubbleCollisionAnimator;
                backGroundAnimator.setRandColor(false);
                break;
            case 15:
                if(fireworkAnimator ==null) {
                    fireworkAnimator = new FireworkAnimator();
                    fireworkAnimator.init(animatorView.getContext(),animatorView);
                    fireworkAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= fireworkAnimator;
                backGroundAnimator.setRandColor(true);
                break;
            case 16:
                if(bubbleCollisionAnimator ==null) {
                    bubbleCollisionAnimator = new BubbleCollisionAnimator();
                    bubbleCollisionAnimator.init(animatorView.getContext(),animatorView);
                    bubbleCollisionAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= bubbleCollisionAnimator;
                backGroundAnimator.setRandColor(true);
                break;
             case 17:
                if(fireworkAnimator ==null) {
                    fireworkAnimator = new FireworkAnimator();
                    fireworkAnimator.init(animatorView.getContext(),animatorView);
                    fireworkAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= fireworkAnimator;
                backGroundAnimator.setRandColor(false);
                break;
            case 18:
                if(dotsLineAnimator ==null) {
                    dotsLineAnimator = new DotsLineAnimator();
                    dotsLineAnimator.init(animatorView.getContext(),animatorView);
                    dotsLineAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= dotsLineAnimator;
                backGroundAnimator.setRandColor(false);
                break;
            case 19:
                if(dotsLineAnimator ==null) {
                    dotsLineAnimator = new DotsLineAnimator();
                    dotsLineAnimator.init(animatorView.getContext(),animatorView);
                    dotsLineAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= dotsLineAnimator;
                backGroundAnimator.setRandColor(true);
                break;
            case 20:
                if(waterAnimator ==null) {
                    waterAnimator = new WaterAnimator();
                    waterAnimator.init(animatorView.getContext(),animatorView);
                    waterAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= waterAnimator;
                backGroundAnimator.setRandColor(true);
                break;
            case 21:
                if(fireAnimator ==null) {
                    fireAnimator = new FireAnimator();
                    fireAnimator.init(animatorView.getContext(),animatorView);
                    fireAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= fireAnimator;
                //backGroundAnimator.setRandColor(true);
                break;
            case 22:
                if(skyAnimator==null) {
                    skyAnimator = new SkyAnimator();
                    skyAnimator.init(animatorView.getContext(),animatorView);
                    skyAnimator.setColor(foregroundColor);
                }
                backGroundAnimator=skyAnimator;
                backGroundAnimator.setRandColor(false);
                break;
            case 23:
                if(rippleAnimator ==null) {
                    rippleAnimator = new RippleAnimator();
                    rippleAnimator.init(animatorView.getContext(),animatorView);
                    rippleAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= rippleAnimator;
                backGroundAnimator.setRandColor(true);
                break;
            case 24:
                if(windmillAnimator ==null) {
                    windmillAnimator = new WindmillAnimator();
                    windmillAnimator.init(animatorView.getContext(),animatorView);
                    windmillAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= windmillAnimator;
                backGroundAnimator.setRandColor(true);
                break;
            case 25:
                if(vorolayAnimator ==null) {
                    vorolayAnimator = new VorolayAnimator();
                    vorolayAnimator.init(animatorView.getContext(),animatorView);
                    vorolayAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= vorolayAnimator;
                backGroundAnimator.setRandColor(true);
                break;
            case 26:
                if(carrouselAnimator ==null) {
                    carrouselAnimator = new CarrouselAnimator();
                    carrouselAnimator.init(animatorView.getContext(),animatorView);
                    carrouselAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= carrouselAnimator;
                backGroundAnimator.setRandColor(true);
                break;
            case 1:
                if(wave3DAnimator ==null) {
                    wave3DAnimator = new Wave3DAnimator();
                    wave3DAnimator.init(animatorView.getContext(),animatorView);
                    wave3DAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= wave3DAnimator;
                backGroundAnimator.setRandColor(true);
                break;

            case 60:
                if(evaporateTextAnimator ==null) {
                    evaporateTextAnimator = new EvaporateTextAnimator();
                    evaporateTextAnimator.init(animatorView.getContext(),animatorView);
                    evaporateTextAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= evaporateTextAnimator;
                backGroundAnimator.setRandColor(true);
                break;

            case 80://以下为特殊动画
                if(eZLedAnimator ==null) {
                    eZLedAnimator = new EZLedAnimator();
                    eZLedAnimator.init(animatorView.getContext(),animatorView);
                    eZLedAnimator.setColor(foregroundColor);
                }
                backGroundAnimator= eZLedAnimator;
                backGroundAnimator.setRandColor(true);
                eZLedAnimator.setText(model.getDescription(),500);
                break;

            default:
                currectAnimatorIndex=0;
                backGroundAnimator=null;
        }
        animatorView.setAnimator(backGroundAnimator);
    }


    ClockAnimator clockAnimator=null;
    //AbstractClock fullScreenClock;
    private void changeFullScreenClock(int index) {
        Log.d(TAG,"changeFullScreenClock index:"+index);

            clockAnimator = new ClockAnimator();
            clockAnimator.init(clockView.getContext(),clockView);
            clockAnimator.setColor(foregroundColor);
        if(index>4)
            currentClockAnimatorIndex=index=0;

        switch (index) {
            case 0:
                clockAnimator.setClock(new CircleClock());
                break;
            case 2:
                clockAnimator.setClock(new OvalClock());
                break;
            case 1:
                clockAnimator.setClock(new SquareClock());
                break;
            //case 3:
            //    clockAnimator.setClock(new OctagonalClock());
            //    break;
            case 3:
                clockAnimator.setClock(new HexagonalClock());
                break;
            case 4:
                clockAnimator.setClock(new HelixClock());
                break;
            default:
                currentClockAnimatorIndex=0;
                clockAnimator=null;
        }
        //currentClockAnimatorIndex=index;
        clockView.setAnimator(clockAnimator);
    }


    private void upHandStatic(){
        if(handUpAbla) {
            this.tv_handup.setColorFilter(foregroundColor);
            //if(hand_time_visable)
            hand_time_visable=true;
            this.tv_hand_time.setVisibility(View.VISIBLE);
        }else{
            this.tv_handup.setColorFilter(R.color.colorPrimaryDark);
            this.tv_hand_time.setVisibility(View.GONE);
        }
    }

    private void resetHandUpTime(){
        this.handUpTime = model.getHandUpTime();
        Log.d(TAG,"reset handUp time:"+handUpTime);
        setDiscriptForModel();
    }

    TimeSetupPopup handUpTimePopup;

    private void setupHandUpTime(){
        int saveHandUpTime=model.getHandUpTime();
        int hour=0;
        int minute=0;
        if(handUpTimePopup==null) {
            handUpTimePopup = new TimeSetupPopup(this);
            handUpTimePopup.setOnSeekBarChangeListener(new TimeSetupPopup.OnTimeChangeListener() {
                @Override
                public void onChanged(int hour, int minute) {
                    model.setHandUpTime(hour*60+minute);
                    handUpAbla=true;
                    if(hour==0&&minute==0) {
                        handUpAbla = false;
                        model.setHandUpTime(-1);
                    }
                    saveData();
                    resetHandUpTime();
                    upHandStatic();
                }
            });
        }
        if(saveHandUpTime>0){
            hour=saveHandUpTime/60;
            minute=saveHandUpTime-hour*60;
        }
        handUpTimePopup.init(hour,minute);
        handUpTimePopup.showPopupWindow();
    }

    private void setupTempHandUpTime(){
        handUpAbla=false;
        int hour=0;
        int minute=0;
        if(handUpTimePopup==null) {
            handUpTimePopup = new TimeSetupPopup(this);
            handUpTimePopup.setOnSeekBarChangeListener(new TimeSetupPopup.OnTimeChangeListener() {
                @Override
                public void onChanged(int hour, int minute) {
                    handUpTime=hour*60+minute;
                }
            });
        }
        hour=handUpTime/60;
        minute=handUpTime-hour*60;
        handUpTimePopup.init(hour,minute);
        handUpTimePopup.showPopupWindow();
        handUpAbla=true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(screenLock)
            return super.onKeyDown(keyCode, event);
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            switchMode(MODE_NORMAL);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
            setup();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void setup(){
        Intent intent = new Intent(this, SettingActivity.class);
        startActivityForResult(intent, SETTING_REQUEST_CODE);
        switchMode(MODE_SETTING_OTHER);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }


    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case UPDATE_TIME:
                updateTime();
                checkHandUp();
                break;
        }
        return true;
    }

    private int handUPDialy=60;

    private void checkHandUp(){
        if(!handUpAbla) {
            return;
        }
        //Log.d(TAG,"checkHandUp..\thandUPDialy:"+handUPDialy+"   \thandUpTime:"+handUpTime+"\thandUpAble:"+handUpAbla);
        if(mMode==MODE_HANDUP) {
            tv_handup_image.setText("hand up:"+handUPDialy);
            handUPDialy--;
            if(handUPDialy==0) {
                switchMode(MODE_NORMAL);
            }else
                Player.getInstance().playHandUp(this);
            return;
        }
        handUpTime--;
        if(hand_time_visable)
            tv_hand_time.setText(DateModel.getTime(handUpTime));
        if (handUpTime <= 10&&handUpTime > 0)
                setDiscript("提醒时间倒计时： " + handUpTime);
        if (handUpTime == 0) {
                handUPDialy = 60;
                resetHandUpTime();
                switchMode(MODE_HANDUP);
        }
    }


    private void setCurrentTimeToView(String timeString){
        if(isArtificialHiddle)
            return;
        if(isFullScreen){
            tv_time.setBaseLineDown(0);
        }else{
            tv_time.setBaseLineDown(tv_day.getHeight()/2);
        }
        tv_time.setText(timeString);
    }


    boolean heartbeat=false;
    private void updateTime() {
        heartbeat=!heartbeat;
        DateModel date = new DateModel();
        String timeString = model.isDisplaySecond() ? date.getTimeString(model.isHourSystem12()) : date.getShortTimeString(heartbeat,model.isHourSystem12());
        setCurrentTimeToView(timeString);
        reportTime(date);
        updateDay(date);
        updateHourSytemStyle(date);
    }

    int beforeHourForUpdateSystem=-1;
    private void updateHourSytemStyle(DateModel date){
        if(model.isHourSystem12()&&beforeHourForUpdateSystem!=date.getHour()) {
            beforeHourForUpdateSystem=date.getHour();
            tv_hours_system.setImageResource(beforeHourForUpdateSystem>12?R.drawable.ic_pm:R.drawable.ic_am);
        }
    }

    DateModel currentDate=null;
    private void updateDay(DateModel date){
        if(currentDate==null||currentDate.getDay()!=date.getDay()) {
            Log.d(TAG,"updateDay."+date);
            currentDate=date;
            String dayString = date.getToday();
            String dateString = date.getDateString();
            if( calendarPopup ==null)
                calendarPopup =new CalendarPopup(this);
            calendarPopup.setCurrentDay();
            String calendarFestival=calendarPopup.getCalendarFestival();
            if(calendarFestival!=null&&!calendarFestival.isEmpty())
                dayString=calendarFestival+"    "+dayString;
            tv_day.setText(dayString);
            tv_date.setText(dateString);
            ClockApplication.getInstance().getBusinessService().getWeather(model.getCity());
        }
    }

    private void setDiscript(String disp){
        tv_descript.setText(disp);
        tv_descript.init(this,false);
        //tv_descript.startScroll();
    }

    private void setDiscriptForModel(){
        String dis=model.getDescription();
        if(dis==null||dis.isEmpty())
            dis=SettingActivity.roundFamousQuotes();
        setDiscript(dis);
    }

    private boolean isReport(int hour, int minute) {

        DateModel startTime = model.getStartHourPowerTime();
        DateModel stopTime = model.getStopHourPowerTime();
        DateModel nowTime = new DateModel();
        nowTime.setTime(hour, minute);

        if (startTime.getShortTimeString().equals(stopTime.getShortTimeString()))
            return true;
        long minutes = startTime.minusTime(stopTime);
        if (minutes < 0) {//stop>start
            if (nowTime.minusTime(startTime) >= 0 && nowTime.minusTime(stopTime) <= 0) {
                return false;
            }
        }
        return true;
    }

    private void reportTime(DateModel date) {
        if (model.isTickSound()) {
            Player.getInstance().playTick(this);
        }
        int year = date.getYear();
        int month = date.getMonth();
        int day = date.getDay();
        int hour = date.getHour();
        int minute = date.getMinute();
        int second = date.getSecond();
        int today = date.getWeek();

        if (model.getTypeHourPower() != Constants.TALKING_NO_REPORT) {
            if ((minute == 30 || minute == 0) && model.getTypeHourPower() == Constants.TALKING_HALF_AN_HOUR && second == 0) {
                Log.d(TAG, String.format("reportTime Year:%d Month:%d Day:%d Hour:%d Minute:%d Today:%d", year, month, day, hour, minute, today));
                if (isReport(hour, minute))
                    Player.getInstance().reportTime(this, year, month, day, hour, minute, today);
            } else if (model.getTypeHourPower() == Constants.TALKING_HOURS && minute == 0 && second == 0) {
                if (isReport(hour, minute))
                    Player.getInstance().reportTime(this, year, month, day, hour, minute, today);
            }
        }
    }

    private void saveData(){
        model.setFontIndex(currentFontIndex);
        model.setHandUpAble(handUpAbla);
        model.save();
    }


    @Override
    public boolean onDown(MotionEvent motionEvent) {

        return false;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }


    @Override
    public void onLongPress(MotionEvent motionEvent) {
        if(screenLock&&isFullScreen) {
            if(tv_time.getVisibility()==View.GONE) {
                changeFullScreenClock(-1);
                tv_time.setVisibility(View.VISIBLE);
                isArtificialHiddle=false;
                clockView.stop();
                clockView.setVisibility(View.GONE);
                return;
            }
            if(particleSmasher==null)
                particleSmasher=new ParticleSmasher(this);
            particleSmasher.with(tv_time).setDuration(1000).addAnimatorListener(new SmashAnimator.OnAnimatorListener() {
                @Override
                public void onAnimatorStart() {
                    super.onAnimatorStart();
                    // 回调，动画开始
                }

                @Override
                public void onAnimatorEnd() {
                    super.onAnimatorEnd();
                    // 回调，动画结束
                    particleSmasher.reShowView(tv_time);
                    tv_time.setVisibility(View.GONE);
                    isArtificialHiddle=true;
                    changeFullScreenClock(currentClockAnimatorIndex++);
                    clockView.setVisibility(View.VISIBLE);
                    clockView.start();
                }
            }).startRandomAnimator();
        }
        if(screenLock)
            return;
        if(!isPowerManagerDisable())
           localWakeLock.isHeld();
        if(mMode==MODE_SETTING_OTHER)
            switchMode(MODE_NORMAL);
        else
           switchMode(MODE_SETTING_OTHER);
    }


    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float v, float v1) {
        if(screenLock&&!isFullScreen)
            return true;
        Log.d(TAG,"onFling");
        if (e2.getY() - e1.getY() < -100) {         // 从上至下
            Log.d(TAG, "change brightness +10");
            brightness = brightness + 10;
            if (brightness >= 255){
                brightness=255;
                Toast.makeText(this,"最大亮度了",Toast.LENGTH_SHORT).show();
                return true;
             }
            changeAppBrightness(brightness);
            return true;
        }else if (e2.getY() - e1.getY() >100) {		 // 从下至上
            Log.d(TAG,"change brightness -10");
            brightness=brightness-10;
            if(brightness<=0) {
                brightness=1;
                Toast.makeText(this,"最小亮度了",Toast.LENGTH_SHORT).show();
                return true;
            }
            changeAppBrightness(brightness);
            return true;
        }
        if (e2.getX() - e1.getX() > 120) {			 // 从左向右滑动（左进右出）
            Log.d(TAG,"left->right");
            if(isFullScreen&&isArtificialHiddle){
                changeFullScreenClock(currentClockAnimatorIndex++);
                return true;
            }

            if(currentFontIndex <fontStyleList.size()-1) {
                currentFontIndex++;
            }else
                currentFontIndex =0;
            saveData();
            this.setFont(currentFontIndex);
            return true;
        } else if (e2.getX() - e1.getX() < -120) {		 // 从右向左滑动（右进左出）
            changeBackGroundAnimator(currectAnimatorIndex++);
            return true;
        }
        return false;
    }


    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        if(!isArtificialHiddle) {
            tv_time.setLinearGradientRandom(!tv_time.isLinearGradientAble());
            return true;
        }
        return false;
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        float span=detector.getCurrentSpan();
        Log.d(TAG,"onScale span:"+span);
        return false;
    }

    float scaleSpan=0;

    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        Log.d(TAG,"onScaleBegin ");
        scaleSpan=detector.getCurrentSpan();

        return true;
    }

    @Override
    public void onScaleEnd(ScaleGestureDetector detector) {
        float fontScale = getResources().getDisplayMetrics().scaledDensity;
        float span=detector.getCurrentSpan()-scaleSpan;
        int step=new Float(span/30).intValue();
        int maxFontSize=getMaxFontSize();
        int baseFontSize=getCurrentFontSize();
        int currentFontSize=new Float(tv_time.getTextSize()/fontScale).intValue();
        currentFontSize=currentFontSize+step;
        Log.d(TAG,"onScaleEnd span:"+span+"\t step:"+step+"\tcurrent text size"+currentFontSize+"\t max text size:"+maxFontSize+"\tmin :"+baseFontSize);
        if(currentFontSize>maxFontSize*1.3){
            currentFontSize=maxFontSize;
        }
        if(currentFontSize<baseFontSize){
            currentFontSize=baseFontSize;
        }
        setFontSize(currentFontSize);
    }


    /**
     * 改变App当前Window亮度
     *
     * @param brightness
     */
    public void changeAppBrightness(int brightness) {
        Window window = this.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        if (brightness == -1) {
            lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
        } else {
            lp.screenBrightness = (brightness <= 0 ? 1 : brightness) / 255f;
        }
        window.setAttributes(lp);
        //Toast.makeText(this,"当前亮度："+getnum(brightness,255),Toast.LENGTH_SHORT).show();
    }

    private int getSystemBrightness() {
        int systemBrightness = 0;
        try {
            systemBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return systemBrightness;
    }

    public String  getnum(int num1,int num2){
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后0位
        numberFormat.setMaximumFractionDigits(0);
        String result = numberFormat.format((float) num1 / (float) num2 * 100);
        return result+"%";
    }

}
